package com.zone.domain.strategy.service.rule.tree.impl;

import com.zone.domain.acticity.repository.IActivityRepository;
import com.zone.domain.strategy.model.valobj.RuleActionEnum;
import com.zone.domain.strategy.repository.IStrategyRepository;
import com.zone.domain.strategy.service.rule.tree.ILogicTreeNode;
import com.zone.domain.strategy.service.rule.tree.factory.DefaultTreeNodeFactory;
import com.zone.types.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: zongzi
 * @description: 抽奖次数锁
 * @date: 2024/6/11
 */
@Slf4j
@Component("rule_lock")
public class RuleLockTreeNode implements ILogicTreeNode {
    @Autowired
    private IStrategyRepository strategyRepository;
    @Autowired
    private IActivityRepository activityRepository;

    @Override
    public DefaultTreeNodeFactory.TreeNodeActionEntity logic(Long strategyId, String userId, Integer awardId, String ruleValue) {
        // 规则配置抽奖次数
        long ruleRaffleCount;
        try {
            ruleRaffleCount = Long.parseLong(ruleValue);
        } catch (NumberFormatException e) {
            throw new BizException("rule lock tree config value error! it must a number!");
        }

        // 奖品信息
        DefaultTreeNodeFactory.StrategyAwardVO strategyAwardVO = DefaultTreeNodeFactory.StrategyAwardVO.builder()
                .awardId(awardId)
                .awardRuleValue(ruleValue)
                .build();

        // 获取当日用户抽奖次数
        Integer userDayRaffleCount = activityRepository.queryUserDayRaffleCount(userId, strategyId);

        // 用户抽奖次数还未达到配置次数，拦截该奖品。
        if (userDayRaffleCount < ruleRaffleCount) {
            return DefaultTreeNodeFactory.TreeNodeActionEntity.builder()
                    .ruleAction(RuleActionEnum.INTERCEPT)
                    .strategyAward(strategyAwardVO)
                    .build();
        } else {
            // 放行请求
            return DefaultTreeNodeFactory.TreeNodeActionEntity.builder()
                    .ruleAction(RuleActionEnum.ALLOW)
                    .strategyAward(strategyAwardVO)
                    .build();
        }
    }
}
